package Util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import pojo.Demo;

import java.io.*;


public class JsonUtil {
    /**
     * author wsz
     * 类转json对象
     * @param obj
     * @return
     */
    public JSON ObjToJson(Object obj){
        //方法一
        JSONObject jsonObject = (JSONObject) JSON.toJSON(obj);
        //方法二
        JSON json = (JSON) JSON.toJSON(obj);
        return json;
    }

    public JSON JosntsrTOObj(String jsonstr){
        JSONObject jsonObject = JSON.parseObject(jsonstr);
        return jsonObject;
    }

    /**
     * 保存josn数据
     * @param fileName
     * @param data
     */
    public void saveDataToFile(String fileName,String data) {
        BufferedWriter writer = null;
        File file = new File("D:\\Myjava\\Homework_Demo\\src\\main\\resources\\"+ fileName + ".json");
        //写入
        try {
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file,false), "UTF-8"));
            writer.write(data);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(writer != null){
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("文件写入成功！");
    }

    /**
     * 读取json文件
     * @param fileName
     * @return
     */
    public String getDatafromFile(String fileName) {

        String Path="D:\\Myjava\\Homework_Demo\\src\\main\\resources\\" + fileName+ ".json";
        BufferedReader reader = null;
        String laststr = "";
        try {
            FileInputStream fileInputStream = new FileInputStream(Path);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
            reader = new BufferedReader(inputStreamReader);
            String tempString = null;
            while ((tempString = reader.readLine()) != null) {
                laststr += tempString;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return laststr;
    }
}
